<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\DbConnection\Db;
use App\Utils\ApiUtils;
use App\Utils\FunctionUtil;
use App\Dao\MenuDao;
use App\Dao\ComponentDao;
use App\Dao\MenuComponentDao;
use App\Dao\DepartComponentDao;
use App\Utils\Redis;
use App\Utils\GRPCClient;
use Pb\Sign;
use Pb\Params;
use Hyperf\Utils\Codec\Json;
use Hyperf\Utils\ApplicationContext;
use App\Dao\AuthAdminLogDao;

class MenuService
{

    /**
     * @Inject
     * @var Redis
     */
    protected $redis;

    /**
     * @Inject
     * @var MenuDao
     */
    protected $menudao;

    /**
     * @Inject
     * @var MenuComponentDao
     */
    protected $mcdao;

    /**
     * @Inject
     * @var ComponentDao
     */
    protected $cdao;

    /**
     * @Inject
     * @var DepartComponentDao
     */
    protected $ddao;

    public function add($params)
    {
        $map = [];
        $map['menu_name'] = $params['menu_name'];
        $map['company_id'] = $params['login_usr']['company_id'];
        $id = $this->menudao->add($map);
        make(AuthAdminLogDao::class)->addLog('添加了栏目'.json_encode($params));
        return ApiUtils::send(ErrorCode::SUCCESS, '添加成功' , $id);
    }

    public function edit($params)
    {
        $where = [];
        $where[] = ['id','=',$params['id']];
        $map['menu_name'] = $params['menu_name'];
        $map['update_time'] = \time();
        $count = $this->menudao->update($where,$map);
        make(AuthAdminLogDao::class)->addLog('编辑了栏目'.json_encode($params));
        return ApiUtils::send(ErrorCode::SUCCESS, '编辑成功' , $count);
        
    }

    public function del($params)
    {
        //先查看下有没有部门关联
        $where2 = [];
        $where2[] = ['menu_id','=',$params['id']];
        $has = $this->mcdao->searchMoudleId($where2);
        if(!empty($has)){
            $res = $this->ddao->searchAll([],$has);
            if(!empty($res)){
                throw new BusinessException(ErrorCode::ERR_BUESSUS, '该栏目被部门绑定，不能删除');
            }
        }
        $where = [];
        $where[] = ['id','=',$params['id']];
        $where1 = [];
        $where1[] = ['menu_id','=',$params['id']];
        Db::beginTransaction();
        try {
            $count = $this->menudao->delete($where);
            $count = $this->mcdao->delete($where1);
            make(AuthAdminLogDao::class)->addLog('删除了栏目'.json_encode($params));
            Db::commit();
            return ApiUtils::send(ErrorCode::SUCCESS, '删除成功' , $count);
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '删除栏目失败'.config('web.err_msg_splite').$e->getMessage());
        }
        
    }

    public function menuAddComponent($params)
    {
        $component = \explode(',',$params['component_id']);
        $component = array_unique($component);
        //找出不可以添加的功能
        $unable = [];
        $unable[] = ['menu_id','!=',$params['menu_id']];
        $unable[] = ['company_id','=',$params['login_usr']['company_id']];
        $unable = $this->mcdao->searchMoudleId($unable);
        $able = array_intersect($component,$unable);
        if(!empty($able)){
            
            throw new BusinessException(ErrorCode::ERR_BUESSUS, implode(',',$able).'模块已被其它栏目选择了');
                 
        }
        Db::beginTransaction();
        try {
            //找出目录之前的功能
            $where = [];
            $where[] = ['menu_id','=',$params['menu_id']];
            $component_ids = $this->mcdao->searchMoudleId($where);

            $del = [];
            $del[] = ['menu_id','=',$params['menu_id']];
            //删除之前
            $this->mcdao->delete($del);
            $map = [];
            $diff = array_diff($component_ids,$component);
            
            if(!empty($diff)){
                //删除部门权限缓存
                $where5 = [];
                $where5[] = ['company_id','=',$params['login_usr']['company_id']];
                $ori = $this->ddao->searchOriId($where5, $diff);
                if(!empty($ori)){
                    foreach($ori as $v){
                        $key_permission = config('web.permission_redis_key').$v;
                        $this->redis->del($key_permission);
                    }
                }
                //删除之前这次没选的模块
                $del1 = [];
                $del1[] = ['company_id','=',$params['login_usr']['company_id']];
                $this->ddao->delete($del1,$diff);
            }
            
            foreach($component as $k => $v){
                if(empty($v)){
                    continue;
                }
                $tmp = [];
                $tmp['component_id'] = $v;
                $tmp['menu_id'] = $params['menu_id'];
                $tmp['company_id'] = $params['login_usr']['company_id'];
                $map[] = $tmp;
            }
            $count = $this->mcdao->insert($map);
            make(AuthAdminLogDao::class)->addLog('栏目添加了功能'.json_encode($params));
            Db::commit();
            return ApiUtils::send(ErrorCode::SUCCESS, '添加成功' , $count);
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '添加功能失败'.config('web.err_msg_splite').$e->getMessage());
        }
         
    }

    public function menuDelComponent($params)
    {
        
        Db::beginTransaction();
        try {
           
            $del = [];
            $del[] = ['menu_id','=',$params['menu_id']];
            $del[] = ['component_id','=',$params['component_id']];
            $this->mcdao->delete($del);
            //删除部门权限缓存
            $where5 = [];
            $where5[] = ['company_id','=',$params['login_usr']['company_id']];
            $ori = $this->ddao->searchOriId($where5, [$params['component_id']]);
            if(!empty($ori)){
                foreach($ori as $v){
                    $key_permission = config('web.permission_redis_key').$v;
                    $this->redis->del($key_permission);
                }
            }
            $del1 = [];
            $del1[] = ['company_id','=',$params['login_usr']['company_id']];
            $del1[] = ['component_id','=',$params['component_id']];
            $count = $this->ddao->delete($del1);
            make(AuthAdminLogDao::class)->addLog('栏目删除了模块'.json_encode($params));
            Db::commit();
            return ApiUtils::send(ErrorCode::SUCCESS, '删除成功' , $count);
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '删除失败'.config('web.err_msg_splite').$e->getMessage());
        }
         
    }

    public function menuMoveComponent($params)
    {
        $where = [];
        $where[] = ['menu_id','=',$params['old_menu_id']];
        $where[] = ['component_id','=',$params['component_id']];
        $count = $this->mcdao->update($where,['menu_id'=>$params['new_menu_id']]);
        //删除部门权限缓存
        $where5 = [];
        $where5[] = ['company_id','=',$params['login_usr']['company_id']];
        $ori = $this->ddao->searchOriId($where5, [$params['component_id']]);
        if(!empty($ori)){
            foreach($ori as $v){
                $key_permission = config('web.permission_redis_key').$v;
                $this->redis->del($key_permission);
            }
        }
        make(AuthAdminLogDao::class)->addLog('移动了栏目模块'.json_encode($params));
        return ApiUtils::send(ErrorCode::SUCCESS, '移动成功' , $count);
       
         
    }

   

    //栏目已被分配的功能
    public function menuHasComponent($params)
    {
        $where[] = ['company_id','=',$params['login_usr']['company_id']];
        $list = $this->mcdao->searchMoudleId($where);
        return ApiUtils::send(ErrorCode::SUCCESS, '获取成功' , $list);
         
    }

    public function move($params)
    {
        $where = [];
        $where[] = ['id','=',$params['id']];
        $has = $this->menudao->searchFirst($where);
        if(empty($has)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '该栏目不存在');
        }
        if($params['type'] == 1){  //上移
            $where1 = [];
            $where1[] = ['sort','>',$has['sort']];
            $where1[] = ['company_id','=',$params['login_usr']['company_id']];
            $next = $this->menudao->MinFirst($where1);
            $update['sort'] = $next['sort'] + 1;
        }else{
            $where1 = [];
            $where1[] = ['sort','<',$has['sort']];
            $where1[] = ['company_id','=',$params['login_usr']['company_id']];
            $next = $this->menudao->MaxFirst($where1);
            $update['sort'] = $next['sort'] - 1;
        }
        $count = $this->menudao->update($where,$update);
        make(AuthAdminLogDao::class)->addLog('移动栏目'.json_encode($params));
        return ApiUtils::send(ErrorCode::SUCCESS, '移动成功' , $count);
         
    }


    public function menuList($params)
    {
        $where[] = ['company_id','=',$params['login_usr']['company_id']];
        $list = $this->menudao->searchAll($where);
        foreach($list as $k => $v){
            if(empty($v['components'])){
                $list[$k]['component'] = [];  
            }else{
                $module_ids = array_column($v['components'],'component_id');
                $data = $this->cdao->searchAll([],$module_ids,['id','content','component_name','icon','pid']);
                $list[$k]['component'] = FunctionUtil::getTree($data);
            }
            unset($list[$k]['components']);
        }
        return ApiUtils::send(ErrorCode::SUCCESS, '获取成功' , $list);

    }

    
}
